import $http from '@/utils/httpRequest'
import $api from '@/utils/api'

const userInfo = uni.getStorageSync('userInfo');
const update = {}
let sfSilent = true

update.downloadTask = null

update.checkUpdate = function({
	silent = true
}){
	sfSilent = silent
	// #ifdef H5
	var terminal = 'H5'
	// #endif
	// #ifdef MP-WEIXIN
	var terminal = 'MP-WEIXIN'
	// #endif
	// #ifdef MP-ALIPAY
	var terminal = 'MP-ALIPAY'
	// #endif
	// #ifdef MP-BAIDU
	var terminal = 'MP-BAIDU'
	// #endif
	// #ifdef MP-TOUTIAO
	var terminal = 'MP-TOUTIAO'
	// #endif
	// ifndef APP-PLUS
	var version = '1000'
/* 	$http.ajax({
		url:$http.adornUrl($api.checkUpdate),
		method:"POST",
		showLoad:!sfSilent,
		data:{
			version:version,
			terminal:terminal,
			userId:userInfo.userId
		}
	}).then(function(data){
		console.log(JSON.stringify(data))
	}) */
	// endif
	// #ifdef APP-PLUS
	const updated = uni.getStorageSync('updated') // 尝试读取storage
	return new Promise((resolve, reject)=>{
		if (updated.completed === true) { // 如果上次刚更新过
			// 删除安装包及安装记录
			uni.removeSavedFile({ 
				filePath: updated.packgePath,
				success: (res) => {
					uni.removeStorageSync('updated')
				}
			})
			sfSilent?"":uni.showToast({title: '请稍后重试'});
		} else if (updated.completed === false) {
			uni.removeStorageSync('updated')
			plus.runtime.install(updated.packgePath, { force: true })
			uni.setStorage({
				key: 'updated',
				data: {
					completed: true,
					packgePath: updated.packgePath
				},
				success: (res) => {
					console.log('成功安装上次的更新，应用需要重启才能继续完成')
				}
			})  
			if(!sfSilent){
				uni.showModal({
					title: '提示',
					content: '应用将重启以完成更新',
					showCancel: false,
					complete: () => {
						plus.runtime.restart()
					}
				})
			}
		} else {
			// 检查更新
			if(!update.downloadTask){
				getWidgetInfo().then(()=>{
					resolve()
				})
			}
		}
	})
	// #endif
}

// #ifdef APP-PLUS
function getWidgetInfo() {
	return new Promise((resolve, reject)=>{
		plus.runtime.getProperty(plus.runtime.appid, wgtinfo => {
			var version = wgtinfo.version
			var terminal = uni.getSystemInfoSync().platform
			detectUpgrade({version:version,terminal:terminal}).then(()=>{
				resolve()
			})
		});
	})
}
function detectUpgrade({version,terminal}){
	return new Promise((resolve, reject)=>{
		$http.ajax({
			url:$http.adornUrl($api.checkUpdate),
			method:"POST",
			showLoad:!sfSilent,
			data:{
				version:version,
				terminal:terminal,
				userId:userInfo.userId
			}
		}).then(function(data){
			console.log(JSON.stringify(data))
			if(data.code == "0"){
				var data = data.data
				if(data){
					if( data.tactics == "hotupdate" && data.addr.match(RegExp(/.wgt/))) {
						hotUpdate({downPath:data.addr}).then(()=>{
							resolve()
						})
					}else{
						uni.showModal({
							title: '提示',
							content: '有新版本需要更新',
							showCancel: false,
							complete: () => {
								plus.runtime.openURL(data.addr)
							}
						})
						if(terminal == 'android' && data.terminal == 'android'){
							
						}else if(terminal == 'ios' && data.terminal == 'ios'){
							
						}
					}
				}else{
					sfSilent?"":uni.showToast({title: '已是最新版本'});
				}
			}
		})
	})	
}
function hotUpdate({downPath}){
	return new Promise((resolve, reject)=>{
		update.downloadTask = uni.downloadFile({
		    url: downPath,
		    success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: (res) => {
							const packgePath = res.savedFilePath
							uni.setStorage({
								key: 'updated',
								data: {
									completed: false,
									packgePath: packgePath
								},
								success: () => {
									console.log('成功保存记录')
								}
							})
							// 任务完成，关闭下载任务
							update.downloadTask.abort()
							update.downloadTask = null
		                }
		            })
		        }
		    },
			fail:()=>{
				// 任务完成，关闭下载任务
				update.downloadTask.abort()
				update.downloadTask = null
			}
		})
		resolve(true)
	})
}
// #endif
export default update